/*
 * 地址选择
 */
'use strict';
import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TouchableHighlight,
    TouchableOpacity,
    Image,
    PixelRatio,
    TextInput,
} from 'react-native';

import Picker from 'react-native-picker';

import Toast from 'antd-mobile/lib/toast';
import List from 'antd-mobile/lib/list';
import InputItem from 'antd-mobile/lib/input-item';
import ActivityIndicator from 'antd-mobile/lib/activity-indicator';

import NavTitle from '../component/NavTitle';

const Item = List.Item;
import { createForm } from 'rc-form';

import XFetch from '../XFetch';

let _selectId;

class Register extends Component {
    constructor(props) {
        super(props)

        this.state = {
            pickerValue: [],
            citys: [],
            provices:[],
            countrys:[],
            streets:[],
            animating:false,
            last:false,
            resultAddr:[]
        }
    }

    componentDidMount(){
        this._changeAddress(0,'provices');
    }

    _register(){
        if(!_selectId){
            Toast.fail('地址未选择',2);
            return;
        }
        this.props.form.validateFields((error, value) => {
            if(!error){
                this.setState({
                    animating:true
                });
                let _body = {
                    ...value,
                    tel:value.tel.replace(/\s/g,''),
                    aid:_selectId,
                }
                let formData = new FormData();

                Object.keys(_body).map(ele=>{
                    formData.append(ele, _body[ele]);
                });
                XFetch(`http://www.weiweigo.com/app/member.aspx?method=reg`,{
                    method:'POST',
                    body:formData
                }).then(data=>{
                    if(data){
                        Toast.success(data, 1);
                        this.setState({
                            animating:false
                        })
                        this.props.navigator.pop();
                    }
                });
            }
        })
    }

    _sendMSG(){
        XFetch(`http://www.weiweigo.com/app/member.aspx?method=getTelCode&tel=${this.props.form.getFieldValue('tel').replace(/\s/g,'')}`,{
            method:'GET',
        }).then(data=>{
            if(data){
                Toast.success(data, 1);
            }
        });
    }

    checkPassword = (rule, value, callback) => {
        const form = this.props.form;
        if (value && value !== form.getFieldValue('pwd')) {
            callback('两次密码不一致!');
            Toast.fail('两次密码不一致',2);
        } else {
            callback();
        }
    }

    _changeAddress(ID=0){
        this.setState({
            animating:true,
        })
        XFetch(`http://www.weiweigo.com/app/address.aspx?method=show&pid=${ID}`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                provices:data.map(ele=>{
                    return {
                        label:ele.NAME,
                        value:ele.ID
                    }
                }),
                animating:false,
            })
        });
    }

    _changeAddress2(ID){
        this.setState({
            animating:true,
        })
        XFetch(`http://www.weiweigo.com/app/address.aspx?method=show&pid=${ID}`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                citys:data.map(ele=>{
                    return {
                        label:ele.NAME,
                        value:ele.ID
                    }
                }),
                animating:false,
            })
        });
    }

    _changeAddress3(ID){
        this.setState({
            animating:true,
        })
        XFetch(`http://www.weiweigo.com/app/address.aspx?method=show&pid=${ID}`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                countrys:data.map(ele=>{
                    return {
                        label:ele.NAME,
                        value:ele.ID
                    }
                }),
                animating:false,
            })
        });
    }

    _changeAddress4(ID){
        this.setState({
            animating:true,
        })
        XFetch(`http://www.weiweigo.com/app/address.aspx?method=show&pid=${ID}`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                streets:data.map(ele=>{
                    return {
                        label:ele.NAME,
                        value:ele.ID
                    }
                }),
                animating:false,
            })
        });
    }

    _selectProvice(){
        let data = [];
        this.state.provices.map(ele=>{
            data.push(ele.label);
        })
        Picker.init({
            pickerData: data,
            pickerConfirmBtnText:'确定',
            pickerCancelBtnText:'取消',
            pickerTitleText:'地址选择',
            onPickerConfirm: data => {
                if(!this.state.resultAddr.some((ele)=>{return ele == data})){
                    this.setState({
                        resultAddr:[data],
                        citys:[],
                        countrys:[],
                        streets:[]
                    },()=>{
                        this.state.provices.map(ele=>{
                            if(ele.label == data){
                                _selectId = null;
                                this._changeAddress2(ele.value);
                            }
                        })
                    })
                }
            },
        });
        Picker.show();
    }

    _selectCity(){
        if(this.state.citys.length == 0){
            Toast.info('请先选择上级',2);
            return;
        }
        let data = [];
        this.state.citys.map(ele=>{
            data.push(ele.label);
        })
        Picker.init({
            pickerData: data,
            pickerConfirmBtnText:'确定',
            pickerCancelBtnText:'取消',
            pickerTitleText:'地址选择',
            onPickerConfirm: data => {
                if(!this.state.resultAddr.some((ele)=>{return ele == data})) {
                    this.setState({
                        resultAddr: [this.state.resultAddr[0], data],
                        countrys:[],
                        streets:[]
                    }, ()=> {
                        this.state.citys.map(ele=> {
                            if (ele.label == data) {
                                _selectId = null;
                                this._changeAddress3(ele.value);
                            }
                        })
                    })
                }
            },
        });
        Picker.show();
    }

    _selectCounty(){
        if(this.state.countrys.length == 0){
            Toast.info('请先选择上级',2);
            return;
        }
        let data = [];
        this.state.countrys.map(ele=>{
            data.push(ele.label);
        })
        Picker.init({
            pickerData: data,
            pickerConfirmBtnText:'确定',
            pickerCancelBtnText:'取消',
            pickerTitleText:'地址选择',
            onPickerConfirm: data => {
                if(!this.state.resultAddr.some((ele)=>{return ele == data})) {
                    this.setState({
                        resultAddr: [this.state.resultAddr[0],this.state.resultAddr[1], data],
                        streets:[]
                    }, ()=> {
                        this.state.countrys.map(ele=> {
                            if (ele.label == data) {
                                _selectId = null;
                                this._changeAddress4(ele.value);
                            }
                        })
                    })
                }
            },
        });
        Picker.show();
    }

    _selectStreet(){
        if(this.state.streets.length == 0){
            Toast.info('请先选择上级',2);
            return;
        }
        let data = [];
        this.state.streets.map(ele=>{
            data.push(ele.label);
        })
        Picker.init({
            pickerData: data,
            pickerConfirmBtnText:'确定',
            pickerCancelBtnText:'取消',
            pickerTitleText:'地址选择',
            onPickerConfirm: data => {
                if(!this.state.resultAddr.some((ele)=>{return ele == data})) {
                    this.state.countrys.map(ele=> {
                        if (ele.label == data) {
                            _selectId = ele.value;
                        }
                    });
                    this.setState({
                        resultAddr: [...this.state.resultAddr, data]
                    });
                }
            },
        });
        Picker.show();
    }

    render() {
        const {getFieldProps} = this.props.form;
        return (
            <View style={styles.container}>
                <NavTitle
                    title='注册'
                    leftButton = {true}
                    leftImg = {require('../imgs/left.png')}
                    leftText = {'返回'}
                    leftHander = {()=>{this.props.navigator.pop()}}
                    headColor = '#fbdc3a'
                />
                <View style={styles.content}>
                        <View style={styles.addressSel}>
                            <TouchableOpacity style={styles.addrlabel} onPress={this._selectProvice.bind(this)}>
                                <Text style={styles.addrIcon}>*</Text>
                                <Text style={styles.addrName}>省份</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.addrlabel} onPress={this._selectCity.bind(this)}>
                                <Text style={styles.addrIcon}>*</Text>
                                <Text style={styles.addrName}>城市</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.addrlabel} onPress={this._selectCounty.bind(this)}>
                                <Text style={styles.addrIcon}>*</Text>
                                <Text style={styles.addrName}>县(区)</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.addrlabel} onPress={this._selectStreet.bind(this)}>
                                <Text style={styles.addrIcon}>*</Text>
                                <Text style={styles.addrName}>镇(街道)</Text>
                            </TouchableOpacity>
                        </View>
                        <View style={{paddingLeft:15,marginTop:10}}>
                            <Text>地址选择:{
                                this.state.resultAddr.join('-')
                            }</Text>
                        </View>
                        <View style={[styles.btnInput]}>
                            <InputItem
                                clear
                                style={[styles.telInput]}
                                placeholder="请输入手机号"
                                type='phone'
                                {...getFieldProps('tel',{
                                    rules: [{required: true}],
                                })}
                                labelNumber={4}
                            />
                            <TouchableOpacity style={styles.sendBtn} onPress={this._sendMSG.bind(this)}>
                                <Text>发送验证码</Text>
                            </TouchableOpacity>
                        </View>

                        <InputItem
                            clear
                            placeholder="验证码"
                            type='number'
                            style={{borderWidth:1/PixelRatio.get(),borderColor:'#ddd',borderRadius:2,paddingLeft:5,marginTop:5}}
                            {...getFieldProps('code',{
                                rules: [{required: true}],
                            })}
                            labelNumber={4}
                            maxLength = {6}
                        />

                        <InputItem
                            clear
                            placeholder="密码"
                            type='password'
                            style={{borderWidth:1/PixelRatio.get(),borderColor:'#ddd',borderRadius:2,paddingLeft:5,marginTop:5}}
                            {...getFieldProps('pwd',{
                                rules: [{required: true}],
                            })}
                            labelNumber={4}
                            maxLength = {20}
                        />

                        <InputItem
                            clear
                            placeholder="重复密码"
                            type='password'
                            style={{borderWidth:1/PixelRatio.get(),borderColor:'#ddd',borderRadius:2,paddingLeft:5,marginTop:5}}
                            {...getFieldProps('cpwd',{
                                rules: [
                                    {required: true},
                                    {validator: this.checkPassword.bind(this),}
                                ],
                            })}
                            labelNumber={4}
                            maxLength = {20}
                        />


                        <TouchableHighlight
                            style={styles.loginBtn}
                            onPress={this._register.bind(this)}
                        >
                            <Text style={styles.loginText}>注册</Text>
                        </TouchableHighlight>
                </View>
                <ActivityIndicator
                    toast
                    text="数据加载中..."
                    animating={this.state.animating}
                />
            </View>
        )
    }

}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#FFF',
        flex: 1,
    },
    itemStyle:{
        flexDirection:'row'
    },
    keys:{
        marginRight:10,
    },
    content:{
        padding:20,
        paddingTop:0
    },
    textInput:{
        padding:5,
        paddingLeft:10,
        borderWidth:1/PixelRatio.get(),
        marginTop:20,
        borderRadius:4,
        borderColor:'#CCC',
        backgroundColor:'#FFF'
    },
    selectInput:{
        backgroundColor:'#FFF',
        marginTop:20,
    },
    loginBtn:{
        padding:15,
        backgroundColor:'#FBDC3A',
        marginTop:20,
        borderRadius:3,
        justifyContent:'center',
        alignItems:'center'
    },
    telInput:{
        flex:1,
        borderWidth:1/PixelRatio.get(),
        borderRadius:4,
        borderColor:'#DDD',
        borderRightWidth:0,
        paddingLeft:5
    },
    btnInput:{
        flexDirection:'row',
        backgroundColor:'#FFF',
        marginTop:10,
    },
    sendBtn:{
        backgroundColor:'#FBDC3A',
        paddingLeft:5,
        paddingRight:5,
        marginLeft:-3,
        justifyContent:'center',
        alignItems:'center',
        borderColor:'#DDD',
        borderBottomWidth:1/PixelRatio.get(),
        borderTopWidth:1/PixelRatio.get(),
        borderRightWidth:1/PixelRatio.get(),
    },
    loginText:{
        fontSize:16
    },
    footTip:{
        flexDirection:'row',
        justifyContent:'flex-end',
        marginTop:10
    },
    tip1:{
        color:'#c9caca'
    },
    tip2:{
        color:'#e83828',
        textDecorationLine:'underline'
    },
    addressSel:{
        flexDirection:'row',
        paddingLeft:15,
        marginTop:10
    },
    addrlabel:{
        flexDirection:'row',
        flex:1
    },
    addrIcon:{
        color: '#F00',
        fontSize:16,
        marginRight:5
    },
    addrName:{
        fontSize:16
    }
});

export default createForm()(Register);
